import {Component} from '@angular/core';
import {IonicPage, NavController, NavParams} from 'ionic-angular';
import {StorageProvider} from "@providers/storage";
import {ImageManipulationProvider} from "@providers/interface/image-manipulation";
import {ImagePickerObject} from "@common/ImagePickerObject";
import {Util} from "@providers/util";
import {WorkerProvider} from "@providers/interface/worker";
import {HttpProvider} from "@providers/http";
import {DialogProvider} from "@providers/dialog";
import {NativeProvider} from "@providers/natives/native";

/**
 * Generated class for the WorkerLookOrderModifyPage PAGE.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-worker-look-order-modify',
  templateUrl: 'worker-look-order-modify.html',
})
export class WorkerLookOrderModifyPage {

  userInfo: any;
  data: any = this.navParams.data;
  picList: any[] = []; //手机当前选中的图片
  picDelList: any[] = []; //手机选择的图片
  picUploadList: any[] = []; //手机选择的图片

  addCode = false;//编码显示控制参数

  typeDataArr: any;//服务性质
  typeData: any;//收卡状态
  min: string = Util.getDate(0);//当天日期
  max: string = Util.getDate(365);//可选最大日期


  faultCause: any[] = [];//故障原因
  maintenancemMeasures: Map<any, any[]> = new Map<any, any[]>();//维修措施
  maintenancemMeasuresByFaultCause: any[] = [];

  num: number;//计数器

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              private storage: StorageProvider,
              private imageMpn: ImageManipulationProvider,
              private dialog: DialogProvider,
              private native: NativeProvider,
              private worker: WorkerProvider,
              private http: HttpProvider) {
    this.data.lift = 1;
    this.userInfo = this.storage.read("userInfo");
    this.data.DHLB = JSON.parse(this.data.DHLB);
    this.data.codeList = JSON.parse(JSON.stringify(this.data.CSM_SORDERITEM));
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad WorkerLookOrderModifyPage');
    this.init();
  }

  /**
   * 数据初始化
   */
  init() {
    this.data.lift = this.data.SFDT;
    this.data.floor = this.data.FLOOR;
    this.data.GZYY = this.data.GZLX;
    this.getCard();
    this.getBranch();
    this.imagedowablelode();

    if (this.data.DESCRIPTION == '维修') {
      this.getFaultCause();
      this.getMaintenancemMeasures();
      this.maintenancemMeasuresByFaultCause = this.maintenancemMeasures.get(this.data.GZYY)||[];
    }
    this.worker.getNJMSFBT().then(message => {
      let data = JSON.parse(JSON.stringify(message))['data'];
      if (!Util.isNull(data)) {
        this.addCode = data[0].ID === '1';
      } else {
        this.addCode = false;
      }
    }).then(() => {
      this.next();
    }).catch(error => {
      this.next();
      console.log(error);
    });
  }

  /**
   * 组合编码参数
   */
  next() {
    for (let i = 0; i < this.data.CSM_SORDERITEM.length; i++) {
      this.nnext(i);
    }
  }

  nnext(item: number) {

    let cd: any = this.data.codeList[item]['NUM'];
    let code = this.data.codeList[item]['codelist'];

    this.num = 0;

    for (let j = 0; j < cd; j++) {
      let ary: any[] = [];
      if (this.data.codeList[item]['codes']) {
        if (this.data.codeList[item]['codes'][j]) {

        } else {
          this.initCode(code, ary);
          this.data.codeList[item].codes.push(ary);
        }
      } else {
        this.initCode(code, ary);
        this.data.codeList[item].codes = [ary];
      }
    }
  }

  /**
   * 初始化codes值
   */
  initCode(code, ary) {
    let length: number;
    if (this.addCode) {
      length = 3;
    } else {
      length = 2;
    }
    for (let k = 0; k < length; k++) {
      if (ary.length == 0) {
        if (code[this.num]) {
          if (code[this.num]['TYPE'] == 1) {
            ary.push({
              "code": code[this.num]['CODE'],
              "lx": "1"
            });
            this.num++;
          } else {
            ary.push({
              "code": '',
              "lx": "1"
            });
          }
        } else {
          ary.push({
            "code": '',
            "lx": "1"
          });
        }
      } else if (ary.length == 1) {
        if (code[this.num]) {
          if (code[this.num]['TYPE'] == 2) {
            ary.push({
              "code": code[this.num]['CODE'],
              "lx": "2"
            });
            this.num++;
          } else {
            ary.push({
              "code": '',
              "lx": "2"
            });
          }
        } else {
          ary.push({
            "code": '',
            "lx": "2"
          });
        }
      } else if (ary.length == 2) {
        if (code[this.num]) {
          if (code[this.num]['TYPE'] == 3) {
            ary.push({
              "code": code[this.num]['CODE'],
              "lx": "3"
            });
            this.num++;
          } else {
            ary.push({
              "code": '',
              "lx": "3"
            });
          }
        } else {
          ary.push({
            "code": '',
            "lx": "3"
          });
        }
      }
    }
  }

  /**
   * 图片加载
   */
  imagedowablelode() {
    this.imageMpn.imagedowablelode({ID: this.data.ID}).then(data => {
      let datas: any[] = data['data'];
      let files: ImagePickerObject[] = [];
      for (let i = 0; i < datas.length; i++) {
        let file = new ImagePickerObject();
        file.url = datas[i]['PICTURE'];
        file.id = datas[i]['XLH'];
        files.push(file);
      }
      this.picList = files
    }).catch(() => {
    });
  }

  /**
   * 图片删除
   */
  delImage(event) {
    this.imageMpn.delImage({XLH: event[0].id}).then(() => {
      //this.imagedowablelode();
    }).catch(() => {
    });
  }

  /**
   * 新增图片
   */
  imageUpload(event) {
    for (let i = 0; i < event.length; i++) {
      this.imageMpn.imageUpload({
        ID: this.data.ID,
        PICTURE: event[i].url
      }).then((data) => {
        event[i].id = data.message;
      }).catch((error) => {
      });
    }
  }

  /**
   * 获取服务性质
   */
  getBranch() {
    this.http.post("/Inbound/invoke.do",
      {
        interfaceId: "csm.css.jcdy.qcfwquery.selectenum",
        data: JSON.stringify({"TYPE": "CSS_FWXZ"})
      }).subscribe(
      message => {
        console.info(message.data);
        this.typeDataArr = message.data;
      },
      error => {
        // this.dialog.showAlert("请选择服务性质");
      });
  }

  /**
   * 获取故障原因
   */
  getFaultCause() {
    this.worker.getFaultCause().then(
      value => {
        let data: any[] = value.data;
        data.forEach(v => {
          this.faultCause.push(v);
        });

        if (this.faultCause.length != 0) {
          this.getMaintenancemMeasures();
        }

      }
    ).catch(e => {
      this.dialog.showAlert("加载故障原因错误");
    });


  }

  /**
   * 得到所有的维修措施
   */
  getMaintenancemMeasures() {

    this.faultCause.forEach(faultCause => {

      this.worker.getMaintenancemMeasures(faultCause.VALUE).then(
        value => {
          let datas: any[] = value.data;
          this.maintenancemMeasures.set(faultCause.VALUE, datas);
        }
      ).catch(
        e => {
          this.dialog.showAlert("获取维修措施错误");
        }
      );

    });
  }

  /**
   * 获取收卡状态
   */
  getCard() {
    this.http.post("/Inbound/invoke.do",
      {
        interfaceId: "csm.css.jcdy.qcfwquery.selectenum",
        data: JSON.stringify({"TYPE": "CSS_SKZT"})
      }).subscribe(
      message => {
        console.info(message.data);
        this.typeData = message.data;
      },
      error => {
        // this.dialog.showAlert("请选择收卡状态");
      });
  }

  /**
   * 修改数据弹出框选择
   * @param data 选择项
   * @param title 标题
   * @param fn 点击事件执行的方法
   */
  updataSelectOption(data: any, title: any, fn: Function) {
    let buttons: any[] = [];

    for (let i = 0; i < this[data].length; i++) {
      buttons.push({
        text: this[data][i]['VALUE'],
        handler: () => {
          fn(this[data][i])
        }
      });
    }
    this.dialog.showActionSheet(buttons, "选择" + title);
  }

  /**
   * 修改服务性质
   */
  updataGuarantee() {

    this.updataSelectOption("typeDataArr", "服务性质", (data) => {
      this.data.FWXZ = data.VALUE;
      this.data.FWXZBM = data.KEY;
    });
  }

  /**
   * 修改收卡状态
   */
  updataCard() {
    this.updataSelectOption("typeData", "收卡状态", (data) => {
      this.data.SKZT = data.VALUE;
      this.data.SKZTBM = data.KEY;
    });
  }

  /**
   * 修改故障原因
   */
  updataCauses() {
    this.updataSelectOption("faultCause", "故障原因", (data) => {
      this.data.GZYY = data.VALUE;
      this.data.GZYYBM = data.KEY;
      this.maintenancemMeasuresByFaultCause = this.maintenancemMeasures.get(data.VALUE)||[];
    });
  }

  /**
   * 修改维修措施
   */
  updataServiceType() {
    if (Util.isNull(this.maintenancemMeasuresByFaultCause)) {
      return this.dialog.showAlert("请先选择故障原因再选择对应维修措施");
    }
    this.updataSelectOption("maintenancemMeasuresByFaultCause", "维修措施", (data) => {
      this.data.WXCS = data.VALUE;
      this.data.WXCSBM = data.KEY;
    });
  }

  /**
   * 扫一扫获取编码
   * @param vcode 编码
   * @param i
   * @param j
   */
  scanBM(vcode: any, i?: any, j?: any) {
    this.native.openScanner().then(v => {
      //vcode.codes[i][j].code = v;
      vcode.code = v;
    }).catch(e => console.log(e));
  }

  /**
   * 输入编码
   * @param vcode 编码
   * @param i
   * @param j
   */
  imputBM(vcode: any, i?: any, j?: any) {
    this.change(false, vcode.code, "编码", (data) => {
      vcode.code = data.data;
    });
  }

  /**
   *修改数据弹窗输入
   * @param item 数据项
   * @param value 显示的数据
   * @param title 数据名
   * @param fn 确认执行的方法
   */
  change(item?: any, value?: any, title?: any, fn?: Function) {
    this.dialog.showRadioOrCheckbox(data => {
        fn(data)
      }, "请输入" + title,
      [{
        name: 'data',
        type: 'text',
        value: item ? this.data[item] : value,
        placeholder: '请输入' + title
      }])
  }

  /**
   * 修改客户地址
   */
  updataAddress() {
    this.change("ADDRESS", null, "客户地址", (data) => {
      this.data.ADDRESS = data.data;
    })
  }

  /**
   * 修改客户手机号
   */
  updataContact() {
    this.change("MOBILE", null, "客户手机号", (data) => {
      this.data.MOBILE = data.data;
    })
  }

  /**
   * 修改客户姓名
   */
  updataName() {
    this.change("NAME", null, "客户姓名", (data) => {
      this.data.NAME = data.data;
    })
  }

  /**
   * 修改楼层
   */
  updataFoolernum() {
    this.change("floor", null, "客户所在楼层", (data) => {
      this.data.floor = data.data;
    })
  }

  /**
   * 修改追加备注
   */
  addRemarks() {
    this.change("BZ", null, "备注", (data) => {
      this.data.BZ = data.data;
    })
  }

  updataYYSJ() {
    document.getElementById('yysj').click();
  }

  /**
   * 拼接数据
   */
  joinedData() {
    let pic: any[] = [];
    for (let i = 0; i < this.picList.length; i++) {
      pic.push(this.picList[i]["url"])
    }
    this.data["picture"] = pic.join(',');
    this.data["CZYMC"] = this.userInfo.username;
  }

  /**
   * 未完工保存
   */
  async saveData() {
    await this.joinedData();
    this.http.post("/Inbound/invoke.do", {
      interfaceId: 'csm.som.cssOrder.makeSorderYCFW',
      data: JSON.stringify(this.data)
    }).subscribe(message => {
      if (message.MSGID == 'S') {
        this.dialog.showAlert("修改成功");
        this.navCtrl.pop();
      } else {
        this.dialog.showAlert("修改失败");
      }
    }, error => {
      this.dialog.showAlert("修改失败");
    });
  }
}
